import React from 'react';
import { Card, Form, Switch, Button, Select, Divider, Row, Col, message } from 'antd';
import { SaveOutlined } from '@ant-design/icons';
import { useUserStore } from '@/store/user';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { authApi } from '@/api/auth';

const { Option } = Select;

const SettingsPage: React.FC = () => {
  const { user } = useUserStore();
  const queryClient = useQueryClient();
  const [form] = Form.useForm();

  // 获取用户设置
  const { data: settings, isLoading } = useQuery({
    queryKey: ['userSettings'],
    queryFn: async () => {
      const response = await authApi.getUserProfile();
      return response;
    },
    enabled: !!user,
  });

  // 更新用户设置
  const updateSettingsMutation = useMutation({
    mutationFn: authApi.updateProfile,
    onSuccess: () => {
      message.success('设置更新成功！');
      queryClient.invalidateQueries({ queryKey: ['userSettings'] });
    },
    onError: () => {
      message.error('更新失败，请重试');
    },
  });

  // 表单提交
  const handleSubmit = async (values: {
    language: string;
    theme: 'light' | 'dark' | 'auto';
    timezone: string;
    notifications: {
      email: boolean;
      push: boolean;
      sms: boolean;
    };
    profileVisibility?: string;
    activityStatus?: boolean;
    onlineStatus?: boolean;
    loginVerification?: string;
    sessionTimeout?: string;
    locationAlert?: boolean;
  }) => {
    try {
      await updateSettingsMutation.mutateAsync(values);
    } catch (error) {
      // 更新失败
    }
  };

  React.useEffect(() => {
    if (settings) {
      form.setFieldsValue({
        language: settings.language || 'zh-CN',
        theme: settings.theme || 'light',
        timezone: settings.timezone || 'Asia/Shanghai',
        notifications: settings.notifications || {
          email: true,
          push: true,
          sms: false,
        },
      });
    }
  }, [settings, form]);

  return (
    <div style={{ height: '100%', width: '100%', overflow: 'auto' }}>
      <Card title="账户设置" loading={isLoading} style={{ height: 'auto' }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          autoComplete="off"
        >
          <Row gutter={24}>
            <Col xs={24} lg={12}>
              <Card title="基本设置" size="small" style={{ marginBottom: 16 }}>
                <Form.Item
                  label="界面语言"
                  name="language"
                  rules={[{ required: true, message: '请选择界面语言' }]}
                >
                  <Select placeholder="请选择界面语言">
                    <Option value="zh-CN">简体中文</Option>
                    <Option value="zh-TW">繁体中文</Option>
                    <Option value="en-US">English</Option>
                    <Option value="ja-JP">日本語</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  label="主题模式"
                  name="theme"
                  rules={[{ required: true, message: '请选择主题模式' }]}
                >
                  <Select placeholder="请选择主题模式">
                    <Option value="light">浅色主题</Option>
                    <Option value="dark">深色主题</Option>
                    <Option value="auto">跟随系统</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  label="时区"
                  name="timezone"
                  rules={[{ required: true, message: '请选择时区' }]}
                >
                  <Select placeholder="请选择时区">
                    <Option value="Asia/Shanghai">北京时间 (UTC+8)</Option>
                    <Option value="Asia/Tokyo">东京时间 (UTC+9)</Option>
                    <Option value="America/New_York">纽约时间 (UTC-5)</Option>
                    <Option value="Europe/London">伦敦时间 (UTC+0)</Option>
                  </Select>
                </Form.Item>
              </Card>
            </Col>

            <Col xs={24} lg={12}>
              <Card title="通知设置" size="small" style={{ marginBottom: 16 }}>
                <Form.Item
                  label="邮件通知"
                  name={['notifications', 'email']}
                  valuePropName="checked"
                >
                  <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                </Form.Item>

                <Form.Item
                  label="推送通知"
                  name={['notifications', 'push']}
                  valuePropName="checked"
                >
                  <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                </Form.Item>

                <Form.Item
                  label="短信通知"
                  name={['notifications', 'sms']}
                  valuePropName="checked"
                >
                  <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                </Form.Item>

                <div style={{ marginTop: 16, padding: 12, backgroundColor: '#f6f6f6', borderRadius: 4 }}>
                  <p style={{ margin: 0, color: '#666', fontSize: 12 }}>
                    💡 提示：开启通知后，您将及时收到系统消息、安全提醒等重要通知。
                  </p>
                </div>
              </Card>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col xs={24} lg={12}>
              <Card title="隐私设置" size="small" style={{ marginBottom: 16 }}>
                <Form.Item
                  label="个人资料可见性"
                  name="profileVisibility"
                >
                  <Select placeholder="请选择个人资料可见性">
                    <Option value="public">公开</Option>
                    <Option value="internal">仅内部可见</Option>
                    <Option value="private">仅自己可见</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  label="活动状态"
                  name="activityStatus"
                  valuePropName="checked"
                >
                  <Switch checkedChildren="显示" unCheckedChildren="隐藏" />
                </Form.Item>

                <Form.Item
                  label="在线状态"
                  name="onlineStatus"
                  valuePropName="checked"
                >
                  <Switch checkedChildren="显示" unCheckedChildren="隐藏" />
                </Form.Item>
              </Card>
            </Col>

            <Col xs={24} lg={12}>
              <Card title="安全设置" size="small" style={{ marginBottom: 16 }}>
                <Form.Item
                  label="登录验证"
                  name="loginVerification"
                >
                  <Select placeholder="请选择登录验证方式">
                    <Option value="password">仅密码</Option>
                    <Option value="2fa">双重验证</Option>
                    <Option value="biometric">生物识别</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  label="会话超时"
                  name="sessionTimeout"
                >
                  <Select placeholder="请选择会话超时时间">
                    <Option value="30">30分钟</Option>
                    <Option value="60">1小时</Option>
                    <Option value="120">2小时</Option>
                    <Option value="480">8小时</Option>
                    <Option value="1440">24小时</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  label="异地登录提醒"
                  name="locationAlert"
                  valuePropName="checked"
                >
                  <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                </Form.Item>
              </Card>
            </Col>
          </Row>

          <Divider />
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              icon={<SaveOutlined />}
              loading={updateSettingsMutation.isPending}
              style={{ marginRight: 8 }}
            >
              保存设置
            </Button>
            <Button
              onClick={() => form.resetFields()}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default SettingsPage;